package org.bee.tl.core;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class FunctionWrapper implements Function{
	Object target;
	Method method;
	boolean isReturnVoid = false ;
	Class[] parameters ;
	boolean requiredContext = false ;
	public FunctionWrapper(Object o,Method m){
		this.target = o;
		this.method = m;
		if(m.getReturnType()==null) isReturnVoid = true;
		parameters = m.getParameterTypes();
		if(parameters.length!=0){
			if(parameters[parameters.length-1].equals(Context.class)){
				requiredContext = true ;
			}
		}
		method.setAccessible(true);
	}
	
	public String getFunctionName(){
		return method.getName();
	}
	@Override
	public Object call(Object[] paras, Context ctx) {
		
		Object[] args = null;
		if(requiredContext){
			args = new Object[paras.length+1];
			for(int i=0;i<paras.length;i++){
				args[i] = paras[i];
			}
			args[args.length-1] = ctx;
		}else{
			args = paras;
		}
		
		try {
			Object result = method.invoke(target, args);
			return result;
		} catch (IllegalArgumentException e) {
			throw new RuntimeException("参数错误"+e.getMessage());
		} catch (IllegalAccessException e) {
			throw new RuntimeException("非法调用"+e.getMessage());
		} catch (InvocationTargetException e) {
			Throwable t = e.getTargetException();
			throw new RuntimeException(t);
		}
		
	}
	
}
